package org.lys.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
 * @Description:单例形式的jdbc连接工具类
 * @Copyright: 福州骏华信息有限公司 (c)2013
 * @Created Date : 2013-4-2
 * @Author lys
 */
public class JdbcUtilsSing {

	private String url = "jdbc:mysql://localhost:3306/javaTest";
	private String user = "root";
	private String password = "root";

	// private static JdbcUtilsSing instance = new JdbcUtilsSing();
	private static JdbcUtilsSing instance = null;

	private JdbcUtilsSing() {
	}
	/**
	 * @Description: 取得实例
	 * @Created Time: 2013-4-2 下午9:12:39
	 * @Author lys
	 * @return
	 */
	public static JdbcUtilsSing getInstance() {
		//延时加载
		if (instance == null) {
			synchronized (JdbcUtilsSing.class) {//多线程加锁
				if (instance == null) {//不能少
					instance = new JdbcUtilsSing();
				}
			}
		}
		return instance;
	}

	static {
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			throw new ExceptionInInitializerError(e);
		}
	}
	/**
	 * @Description: 取得数据库连接
	 * @Created Time: 2013-4-2 下午9:11:34
	 * @Author lys
	 * @return
	 * @throws SQLException
	 */
	public Connection getConnection() throws SQLException {
		return DriverManager.getConnection(url, user, password);
	}
	/**
	 * @Description: 释放资源
	 * @Created Time: 2013-4-2 下午9:11:51
	 * @Author lys
	 * @param rs
	 * @param st
	 * @param conn
	 */
	public void free(ResultSet rs, Statement st, Connection conn) {
		try {
			if (rs != null)
				rs.close();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (st != null)
					st.close();
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				if (conn != null)
					try {
						conn.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
			}
		}
	}
}
